package com.zerui.manager.common.entity;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zerui.authority.context.LoginUserHolder;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 自动填充处理类
 * myBatisMetaObjectHandler,myMetaObjectHandler
 **/
@Component
public class MyBatisMetaObjectHandler implements MetaObjectHandler {

    public static final String IS_DELETE = "isDelete";
    public static final String CREATE_TIME = "createTime";
    public static final String UPDATE_TIME = "updateTime";
    public static final String CREATE_BY = "createBy";
    public static final String UPDATE_BY = "updateBy";

    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasSetter(IS_DELETE)) {
            this.strictInsertFill(metaObject, IS_DELETE, Boolean.class, false);
        }
        if (metaObject.hasSetter(CREATE_TIME)) {
            this.strictInsertFill(metaObject, CREATE_TIME, LocalDateTime.class,
                LocalDateTime.now());
        }
        if (metaObject.hasSetter(UPDATE_TIME)) {
            this.strictInsertFill(metaObject, UPDATE_TIME, LocalDateTime.class,
                LocalDateTime.now());
        }
        if (metaObject.hasSetter(CREATE_BY)) {
            this.strictInsertFill(metaObject, CREATE_BY, String.class,
                LoginUserHolder.get().getUsername());
        }
        if (metaObject.hasSetter(UPDATE_BY)) {
            this.strictInsertFill(metaObject, UPDATE_BY, String.class,
                LoginUserHolder.get().getUsername());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasSetter(UPDATE_TIME)) {
            this.strictUpdateFill(metaObject, UPDATE_TIME, LocalDateTime.class,
                LocalDateTime.now());
        }
        if (metaObject.hasSetter(UPDATE_BY)) {
            this.strictUpdateFill(metaObject, UPDATE_BY, String.class,
                LoginUserHolder.get().getUsername());
        }
    }
}
